<template>
  <div>
    <div class="card" style="margin-bottom: 5px;">
      <el-input v-model="name" style="width: 300px; margin-right: 10px" placeholder="请输入名称查询"></el-input>
      <el-button type="primary" @click="load">查询</el-button>
      <el-button type="info" style="margin: 0 10px" @click="reset">重置</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <div style="margin-bottom: 10px">
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </div>
      <el-table :data="tableData" stripe>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="名称" prop="name"></el-table-column>
        <el-table-column label="角色" prop="role">
          <template slot-scope="scope">
            <span v-if="scope.row.role === 'ADMIN'">管理员</span>
            <span v-else-if="scope.row.role === 'USER'">普通用户</span>
            <span v-else-if="scope.row.role === 'VISITOR'">访客</span>
            <span v-else>{{ scope.row.role }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="450">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
            <el-button type="warning" size="small" @click="handlePasswordReset(scope.row)">密码更新</el-button>
            <el-button type="info" size="small" @click="handleRoleBinding(scope.row)">绑定角色</el-button>
            <el-button type="success" size="small" @click="handleDeptBinding(scope.row)">绑定部门</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="card">
      <el-pagination background layout="prev, pager, next" :page-size="pageSize" :current-page="pageNum" :total="total"
        @current-change="handlePageChange">
      </el-pagination>
    </div>

    <el-dialog title="信息" width="40%" :visible.sync="formVisible" :close-on-click-modal="false">
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="100px" style="padding-right: 50px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template slot="footer">
        <span class="dialog-footer">
          <el-button @click="formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 密码重置对话框 -->
    <el-dialog title="密码重置" width="40%" :visible.sync="passwordResetVisible" :close-on-click-modal="false">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
        <el-form-item label="用户名" :disabled="true">
          <el-input v-model="passwordForm.username" disabled />
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="passwordForm.password" type="password" autocomplete="new-password" placeholder="请输入新密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" />
        </el-form-item>
      </el-form>
      <template slot="footer">
        <span class="dialog-footer">
          <el-button @click="passwordResetVisible = false">取 消</el-button>
          <el-button type="primary" @click="resetPassword">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 角色绑定对话框 -->
    <el-dialog title="角色绑定" width="40%" :visible.sync="roleBindingVisible" :close-on-click-modal="false">
      <el-form :model="roleForm" :rules="roleRules" ref="roleFormRef" label-width="100px">
        <el-form-item label="用户名" :disabled="true">
          <el-input v-model="roleForm.username" disabled />
        </el-form-item>
        <el-form-item label="选择角色" prop="role">
          <el-radio-group v-model="roleForm.role">
            <el-radio label="ADMIN">管理员</el-radio>
            <el-radio label="USER">普通用户</el-radio>
            <el-radio label="VISITOR">访客</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <span class="dialog-footer">
          <el-button @click="roleBindingVisible = false">取 消</el-button>
          <el-button type="primary" @click="bindRole">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 部门绑定对话框 -->
    <el-dialog title="部门绑定" width="40%" :visible.sync="deptBindingVisible" :close-on-click-modal="false">
      <el-form :model="deptForm" :rules="deptRules" ref="deptFormRef" label-width="100px">
        <el-form-item label="用户名" :disabled="true">
          <el-input v-model="deptForm.username" disabled />
        </el-form-item>
        <el-form-item label="选择部门" prop="department">
          <el-select v-model="deptForm.department" placeholder="请选择部门">
            <el-option label="技术部" value="TECH" />
            <el-option label="市场部" value="MARKET" />
            <el-option label="财务部" value="FINANCE" />
            <el-option label="人力资源部" value="HR" />
          </el-select>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <span class="dialog-footer">
          <el-button @click="deptBindingVisible = false">取 消</el-button>
          <el-button type="primary" @click="bindDepartment">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { MessageBox, Message } from "element-ui";
import userApi from '@/api/user'; // 导入API模块

export default {
  data() {
    return {
      pageNum: 1,
      pageSize: 10,
      total: 0,
      formVisible: false,
      form: {},
      tableData: [],
      passwordResetVisible: false,
      passwordForm: {
        id: '',
        username: '',
        password: '',
        confirmPassword: ''
      },
      roleBindingVisible: false,
      roleForm: {
        id: '',
        username: '',
        role: ''
      },
      deptBindingVisible: false,
      deptForm: {
        id: '',
        username: '',
        department: ''
      },
      name: null,
      // 表单验证规则
      formRules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 2, max: 20, message: '账号长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 2, max: 20, message: '名称长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      },
      passwordRules: {
        password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ]
      },
      roleRules: {
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      },
      deptRules: {
        department: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ]
      },
      // 模拟数据 - 当API调用失败时使用
      mockUsers: [
        {
          id: '1',
          username: 'admin',
          name: '管理员',
          role: 'ADMIN',
          department: 'TECH'
        },
        {
          id: '2',
          username: 'user1',
          name: '张三',
          role: 'USER',
          department: 'TECH'
        },
        {
          id: '3',
          username: 'user2',
          name: '李四',
          role: 'USER',
          department: 'MARKET'
        },
        {
          id: '4',
          username: 'user3',
          name: '王五',
          role: 'VISITOR',
          department: 'FINANCE'
        }
      ]
    }
  },
  methods: {
    // 验证确认密码
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.passwordForm.password) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    },
    
    // 列表查询接口 - 使用API模块
    load() {
      try {
        userApi.list({
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name
        }).then(res => {
          if (res && res.code === 200) {
            this.tableData = res?.data?.list || [];
            this.total = res?.data?.total || 0;
          } else {
            Message.warning('获取用户列表失败，使用模拟数据');
            this.useMockData();
          }
        }).catch(error => {
          console.error('获取用户列表出错:', error);
          Message.warning('获取用户列表失败，使用模拟数据');
          this.useMockData();
        })
      } catch (error) {
        console.error('加载数据出错:', error);
        Message.warning('加载数据失败，使用模拟数据');
        this.useMockData();
      }
    },
    
    /** 使用模拟数据 */
    useMockData() {
      // 根据查询条件过滤模拟数据
      let filteredData = this.mockUsers;
      if (this.name) {
        filteredData = filteredData.filter(user => 
          user.name.includes(this.name) || user.username.includes(this.name)
        );
      }
      
      // 处理分页
      const startIndex = (this.pageNum - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      this.tableData = filteredData.slice(startIndex, endIndex);
      this.total = filteredData.length;
    },
    
    handleAdd() {
      this.form = {};
      this.formVisible = true;
    },
    
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row));
      this.formVisible = true;
    },
    
    // 新增用户信息接口 - 使用API模块
    add() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          try {
            userApi.add(this.form).then(res => {
              if (res && res.code === 200) {
                Message.success('添加成功');
                this.formVisible = false;
                this.load();
              } else {
                Message.error('添加失败：' + (res?.message || '未知错误'));
              }
            }).catch(error => {
              console.error('添加用户出错:', error);
              Message.error('添加用户失败');
            });
          } catch (error) {
            console.error('添加用户出错:', error);
            Message.error('添加用户失败');
          }
        }
      });
    },
    
    // 用户信息更新接口 - 使用API模块
    update() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          try {
            userApi.update(this.form).then(res => {
              if (res && res.code === 200) {
                Message.success('更新成功');
                this.formVisible = false;
                this.load();
              } else {
                Message.error('更新失败：' + (res?.message || '未知错误'));
              }
            }).catch(error => {
              console.error('更新用户出错:', error);
              Message.error('更新用户失败');
            });
          } catch (error) {
            console.error('更新用户出错:', error);
            Message.error('更新用户失败');
          }
        }
      });
    },
    
    save() {
      this.form.id ? this.update() : this.add();
    },
    
    // 用户信息删除接口 - 使用API模块
    handleDelete(id) {
      // 防止删除管理员账号
      if (id === '1') {
        Message.error('管理员账号不能删除');
        return;
      }
      
      MessageBox.confirm('删除后数据无法恢复，您确定删除吗?', '删除确认', { type: 'warning' }).then(() => {
        try {
          userApi.delete(id).then(res => {
            if (res && res.code === 200) {
              Message.success('删除成功');
              this.load();
            } else {
              Message.error('删除失败：' + (res?.message || '未知错误'));
            }
          }).catch(error => {
            console.error('删除用户出错:', error);
            Message.error('删除用户失败');
          });
        } catch (error) {
          console.error('删除用户出错:', error);
          Message.error('删除用户失败');
        }
      }).catch(() => { });
    },
    
    reset() {
      this.name = null;
      this.load();
    },
    
    handlePageChange(val) {
      this.pageNum = val;
      this.load();
    },
    
    handlePasswordReset(row) {
      this.passwordForm = {
        id: row.id,
        username: row.username,
        password: '',
        confirmPassword: ''
      };
      this.passwordResetVisible = true;
    },
    
    // 密码更新接口 - 使用API模块
    resetPassword() {
      this.$refs.passwordFormRef.validate(valid => {
        if (valid) {
          try {
            const { id, password } = this.passwordForm;
            userApi.updatePassword({ id, password }).then(res => {
              if (res && res.code === 200) {
                Message.success('密码重置成功');
                this.passwordResetVisible = false;
              } else {
                Message.error('密码重置失败：' + (res?.message || '未知错误'));
              }
            }).catch(error => {
              console.error('密码重置出错:', error);
              Message.error('密码重置失败');
            });
          } catch (error) {
            console.error('密码重置出错:', error);
            Message.error('密码重置失败');
          }
        }
      });
    },
    
    handleRoleBinding(row) {
      this.roleForm = {
        id: row.id,
        username: row.username,
        role: row.role || 'USER'
      };
      this.roleBindingVisible = true;
    },
    
    // 用户绑定角色接口 - 使用API模块
    bindRole() {
      this.$refs.roleFormRef.validate(valid => {
        if (valid) {
          try {
            const { id, role } = this.roleForm;
            userApi.addRole({ id, role }).then(res => {
              if (res && res.code === 200) {
                Message.success('角色绑定成功');
                this.roleBindingVisible = false;
                this.load();
              } else {
                Message.error('角色绑定失败：' + (res?.message || '未知错误'));
              }
            }).catch(error => {
              console.error('角色绑定出错:', error);
              Message.error('角色绑定失败');
            });
          } catch (error) {
            console.error('角色绑定出错:', error);
            Message.error('角色绑定失败');
          }
        }
      });
    },
    
    handleDeptBinding(row) {
      this.deptForm = {
        id: row.id,
        username: row.username,
        department: row.deptId || ''
      };
      this.deptBindingVisible = true;
    },
    
    // 用户绑定部门接口 - 使用API模块
    bindDepartment() {
      this.$refs.deptFormRef.validate(valid => {
        if (valid) {
          try {
            const { id, department } = this.deptForm;
            userApi.addDept({ id, deptId: department }).then(res => {
              if (res && res.code === 200) {
                Message.success('部门绑定成功');
                this.deptBindingVisible = false;
                this.load();
              } else {
                Message.error('部门绑定失败：' + (res?.message || '未知错误'));
              }
            }).catch(error => {
              console.error('部门绑定出错:', error);
              Message.error('部门绑定失败');
            });
          } catch (error) {
            console.error('部门绑定出错:', error);
            Message.error('部门绑定失败');
          }
        }
      });
    }
  },
  
  created() {
    this.load();
  }
}
</script>

<style scoped>
.card {
  background-color: #fff;
  border-radius: 5px;
  padding: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, .1);
}

/* 调整操作列按钮样式，使它们更好地排成一行 */
.el-button--small {
  margin-right: 5px;
}
</style>